#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RagFlow客户端跨平台打包脚本
支持Mac、Linux和Windows平台
"""

import os
import sys
import shutil
import platform
import argparse
import subprocess
from pathlib import Path

def run_command(cmd):
    """运行命令并打印输出"""
    print(f"执行命令: {cmd}")
    process = subprocess.Popen(
        cmd, 
        shell=True, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.STDOUT, 
        universal_newlines=True
    )
    
    for line in process.stdout:
        print(line.strip())
    
    process.wait()
    return process.returncode

def clean_build_dirs():
    """清理构建目录"""
    dirs_to_clean = ['build', 'dist']
    for dir_name in dirs_to_clean:
        if os.path.exists(dir_name):
            print(f"清理目录: {dir_name}")
            shutil.rmtree(dir_name)

def install_requirements():
    """安装打包所需的依赖"""
    print("安装打包所需的依赖...")
    run_command("pip install pyinstaller")

def detect_platform():
    """检测当前平台"""
    system = platform.system().lower()
    if system == "darwin":
        return "mac"
    elif system == "linux":
        return "linux"
    elif system == "windows":
        return "windows"
    else:
        print(f"不支持的平台: {system}")
        sys.exit(1)

def create_icon_files():
    """创建图标文件（如果不存在）"""
    resources_dir = Path("resources")
    resources_dir.mkdir(exist_ok=True)
    
    # 这里可以添加代码来生成图标文件
    # 如果没有图标文件，可以使用默认图标或者提示用户添加

def create_default_config():
    """创建默认配置文件"""
    # 创建默认配置文件
    if not os.path.exists(".env"):
        print("创建默认配置文件: .env")
        with open(".env", "w", encoding="utf-8") as f:
            f.write("# RagFlow 配置文件\n")
            f.write("RAGFLOW_API_URL=\n")
            f.write("RAGFLOW_API_KEY=\n")
            f.write("RAGFLOW_KB_ID=\n")
            f.write("RAGFLOW_KB_NAME=\n")
            f.write("RAGFLOW_PARSER_ID=naive\n")
            f.write("RAGFLOW_DOC_DIR=\n")
            f.write("RAGFLOW_DOC_SUFFIX=md,txt,pdf,docx\n")
            f.write("THEME=light\n")
            f.write("DEBUG=false\n")

def build_with_pyinstaller(use_spec=True, onefile=False):
    """使用PyInstaller构建应用程序"""
    cmd = "pyinstaller --clean "
    
    if use_spec:
        cmd += "ragflow.spec"
    else:
        # 基本的PyInstaller命令
        cmd += "--noconfirm "
        
        if onefile:
            cmd += "--onefile "
        else:
            cmd += "--onedir "
        
        # 添加图标
        platform_name = detect_platform()
        if platform_name == "mac" and os.path.exists("resources/icon.icns"):
            cmd += "--icon=resources/icon.icns "
        elif platform_name == "windows" and os.path.exists("resources/icon.ico"):
            cmd += "--icon=resources/icon.ico "
        
        # 添加平台特定选项
        if platform_name in ["mac", "windows"]:
            cmd += "--windowed "  # GUI模式
        
        # 添加数据文件
        cmd += "--add-data resources:resources "
        
        # 如果存在.env文件，也添加到数据文件中
        if os.path.exists(".env"):
            if platform_name == "windows":
                cmd += "--add-data .env;. "
            else:
                cmd += "--add-data .env:. "
        
        # 添加应用程序名称和入口点
        cmd += "--name RagFlow "
        cmd += "ragflow_client/__main__.py"
    
    # 执行构建命令
    return run_command(cmd)

def create_distribution_package(platform_name):
    """创建分发包"""
    dist_dir = Path("dist")
    if not dist_dir.exists():
        print("错误: dist目录不存在，构建可能失败")
        return False
    
    # 创建版本号
    version = "1.0.0"  # 可以从项目配置或命令行参数获取
    
    # 创建分发包名称
    package_name = f"RagFlow-{version}-{platform_name}"
    package_dir = dist_dir / package_name
    
    # 创建分发包目录
    if package_dir.exists():
        shutil.rmtree(package_dir)
    package_dir.mkdir()
    
    # 复制构建结果到分发包目录
    if platform_name == "mac":
        # 复制.app包
        app_path = dist_dir / "RagFlow.app"
        if app_path.exists():
            shutil.copytree(app_path, package_dir / "RagFlow.app")
        else:
            print("错误: RagFlow.app不存在")
            return False
    elif platform_name == "windows":
        # 复制RagFlow目录
        ragflow_dir = dist_dir / "RagFlow"
        if ragflow_dir.exists():
            shutil.copytree(ragflow_dir, package_dir / "RagFlow")
        else:
            print("错误: RagFlow目录不存在")
            return False
    else:  # linux
        # 复制RagFlow目录
        ragflow_dir = dist_dir / "RagFlow"
        if ragflow_dir.exists():
            shutil.copytree(ragflow_dir, package_dir / "RagFlow")
        else:
            print("错误: RagFlow目录不存在")
            return False
    
    # 复制README和其他文档
    if Path("README.md").exists():
        shutil.copy("README.md", package_dir)
    
    # 创建压缩包
    archive_name = f"{package_name}"
    shutil.make_archive(archive_name, "zip", dist_dir, package_name)
    
    print(f"分发包已创建: {archive_name}.zip")
    return True

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="RagFlow客户端打包工具")
    parser.add_argument("--clean", action="store_true", help="清理构建目录")
    parser.add_argument("--spec", action="store_true", help="使用spec文件构建")
    parser.add_argument("--onefile", action="store_true", help="创建单文件可执行文件")
    parser.add_argument("--package", action="store_true", help="创建分发包")
    
    args = parser.parse_args()
    
    # 检测当前平台
    current_platform = detect_platform()
    print(f"当前平台: {current_platform}")
    
    # 清理构建目录
    if args.clean:
        clean_build_dirs()
    
    # 安装依赖
    install_requirements()
    
    # 创建图标文件
    create_icon_files()
    
    # 构建应用程序
    result = build_with_pyinstaller(use_spec=args.spec, onefile=args.onefile)
    
    if result == 0:
        print("\n构建成功!")
        
        # 创建分发包
        if args.package:
            if create_distribution_package(current_platform):
                print("分发包创建成功!")
            else:
                print("分发包创建失败!")
                sys.exit(1)
        
        if current_platform == "mac":
            print("可执行文件位于: dist/RagFlow.app")
        elif current_platform == "windows":
            print("可执行文件位于: dist/RagFlow/RagFlow.exe")
        else:
            print("可执行文件位于: dist/RagFlow/RagFlow")
    else:
        print("\n构建失败!")
        sys.exit(1)

if __name__ == "__main__":
    main()